import { Injectable } from '@nestjs/common';
import { CreateBookDto } from './dto/create-book.dto';
import { UpdateBookDto } from './dto/update-book.dto';
import { Repository } from 'typeorm';
import { Book } from './entities/book.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { SearchMatchFlag } from '../type';

@Injectable()
export class BookService {
  constructor(
    @InjectRepository(Book) private bookRepository: Repository<Book>,
  ) {}

  create(createBookDto: CreateBookDto) {
    const newBook: Book = new Book();
    newBook.code = createBookDto.code;
    newBook.name = createBookDto.name;
    newBook.institute = createBookDto.institute;
    newBook.major = createBookDto.major;
    newBook.credit = createBookDto.credit;
    newBook.period = createBookDto.period;
    newBook.characteristics = createBookDto.characteristics;
    newBook.courseType = createBookDto.courseType;
    newBook.prerequisite = createBookDto.prerequisite;
    newBook.textbook = createBookDto.textbook;
    newBook.textbookFormatInfo = createBookDto.textbookFormatInfo;
    newBook.textbookWebsite = createBookDto.textbookWebsite;
    newBook.reference = createBookDto.reference;
    newBook.referenceFormatInfo = createBookDto.referenceFormatInfo;
    newBook.referenceWebsite = createBookDto.referenceWebsite;
    newBook.newestReference = createBookDto.newestReference;
    newBook.newestReferenceWebsite = createBookDto.newestReferenceWebsite;
    return this.bookRepository.save(newBook);
  }

  findAll() {
    return this.bookRepository.find();
  }

  findOne(id: string) {
    return this.bookRepository
      .createQueryBuilder('aBook')
      .where('aBook.id = :id', { id })
      .getOne();
  }

  findOneFromName(name: string) {
    return this.bookRepository
      .createQueryBuilder('aBook')
      .where('aBook.name like :param')
      .setParameters({
        param: '%' + name + '%',
      })
      .getOne();
  }

  findManyFromMatchFlagAndInfo(matchFlag: SearchMatchFlag, info: string) {
    return this.bookRepository
      .createQueryBuilder('aBook')
      .where(
        `aBook.${JSON.stringify(matchFlag).substring(
          1,
          JSON.stringify(matchFlag).length - 1,
        )} like :param`,
      )
      .setParameters({
        param: '%' + info + '%',
      })
      .getMany();
  }

  update(id: number, updateBookDto: UpdateBookDto) {
    return `This action updates a #${id} book`;
  }

  remove(id: number) {
    return `This action removes a #${id} book`;
  }
}
